package com.yc.testupload.controller;

import com.yc.testupload.model.Account;
import com.yc.testupload.model.PublishResult;
import com.yc.testupload.publisher.PlatformPublisher;
import com.yc.testupload.publisher.PlatformPublisherFactory;
import com.yc.testupload.service.WechatPublishProducer;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 内容发布Servlet
 * 处理来自前端的发布请求，调用相应平台的发布器进行内容发布
 */
@WebServlet(name = "publishServlet", value = "/api/publish")
public class PublishServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(PublishServlet.class);
    private PlatformPublisherFactory publisherFactory;
    private WechatPublishProducer publishProducer;

    @Override
    public void init() throws ServletException {
        super.init();
        // 初始化发布器工厂
        publisherFactory = new PlatformPublisherFactory();
        // 初始化发布任务生产者
        publishProducer = new WechatPublishProducer();
        logger.info("PublishServlet 初始化完成");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域访问
        PrintWriter out = response.getWriter();

        try {
            // 读取请求体
            StringBuilder requestBody = new StringBuilder();
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }

            // 解析JSON数据
            JSONObject jsonObject = new JSONObject(requestBody.toString());
            
            // 检查是否为批量发布格式
            boolean isBatch = jsonObject.optBoolean("isBatch", false);
            
            StringBuilder platformResponses = new StringBuilder();
            boolean allSuccess = true;
            
            List<String> taskIds = new ArrayList<>();
            
            if (isBatch || jsonObject.has("documents") || jsonObject.has("platforms")) {
                // 处理批量发布或包含documents/platforms格式的请求
                JSONArray documentsArray = jsonObject.getJSONArray("documents");
                JSONArray platformsArray = jsonObject.getJSONArray("platforms");
                
                logger.info("接收到批量发布请求，文档数量: {}, 平台数量: {}", documentsArray.length(), platformsArray.length());
                
                // 遍历每个文档
                for (int i = 0; i < documentsArray.length(); i++) {
                    JSONObject document = documentsArray.getJSONObject(i);
                    String title = document.optString("title", "未命名文档");
                    String content = document.optString("content", "");
                    
                    // 遍历每个选中的平台
                    for (int j = 0; j < platformsArray.length(); j++) {
                        String platformId = platformsArray.getString(j);
                        
                        // 这里需要根据platformId获取平台信息（账号和平台类型）
                        // 由于前端传递的是platformId，我们需要模拟构建Account对象
                        // 实际项目中应该从数据库获取账号信息
                        Account account = createMockAccountFromPlatformId(platformId);
                        
                        if (account != null) {
                            // 创建发布内容Map
                            Map<String, Object> publishContent = new HashMap<>();
                            publishContent.put("title", title);
                            publishContent.put("content", content);
                            publishContent.put("accountId", account.getAccountId());
                            publishContent.put("accountName", account.getAccountName());
                            publishContent.put("platformType", account.getAccountType());
                            publishContent.put("platformId", platformId);
                            
                            // 异步发送到消息队列
                            String taskId = publishProducer.sendPublishTask(publishContent);
                            taskIds.add(taskId);
                            
                            // 收集发布任务信息
                            if (platformResponses.length() > 0) {
                                platformResponses.append("\n");
                            }
                            platformResponses.append(String.format("%s -> %s: 发布任务已提交，任务ID: %s", 
                                    title, account.getAccountName(), taskId));
                        }
                    }
                }
            } else {
                // 处理单个文档发布（旧格式）
                // 创建Account对象
                JSONObject accountJson = jsonObject.getJSONObject("account");
                Account account = new Account();
                account.setAccountId(accountJson.getString("accountId"));
                account.setAccountName(accountJson.getString("accountName"));
                account.setAccountType(accountJson.getString("platformType"));
                
                // 创建发布内容Map
                Map<String, Object> content = new HashMap<>();
                content.put("title", jsonObject.getString("title"));
                content.put("content", jsonObject.getString("content"));
                content.put("accountId", account.getAccountId());
                content.put("accountName", account.getAccountName());
                content.put("platformType", account.getAccountType());
                
                // 异步发送到消息队列
                String taskId = publishProducer.sendPublishTask(content);
                taskIds.add(taskId);
                platformResponses.append("发布任务已提交，任务ID: " + taskId);
                allSuccess = true; // 异步模式下，提交成功即返回成功
            }
            
            // 构造响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", allSuccess);
            responseJson.put("message", "发布任务已异步提交，请稍后查看发布结果");
            responseJson.put("platformResponse", platformResponses.toString());
            responseJson.put("taskIds", new JSONArray(taskIds));
            
            // 返回响应
            out.println(responseJson.toString());
            
        } catch (Exception e) {
            logger.error("发布过程中发生错误: {}", e.getMessage(), e);
            
            // 返回错误响应
            JSONObject errorJson = new JSONObject();
            errorJson.put("success", false);
            errorJson.put("message", "发布失败: " + e.getMessage());
            
            out.println(errorJson.toString());
        } finally {
            out.close();
        }
    }
    
    /**
     * 根据platformId模拟创建Account对象
     * 实际项目中应该从数据库获取账号信息
     */
    private Account createMockAccountFromPlatformId(String platformId) {
        Account account = new Account();
        account.setAccountId(platformId);
        
        // 根据platformId末尾数字判断平台类型（简单模拟）
        if (platformId.endsWith("1") || platformId.contains("wechat")) {
            account.setAccountType("wechat");
            account.setAccountName("微信测试账号");
        } else if (platformId.endsWith("2") || platformId.contains("weibo")) {
            account.setAccountType("weibo");
            account.setAccountName("微博测试账号");
        } else if (platformId.endsWith("3") || platformId.contains("douyin")) {
            account.setAccountType("douyin");
            account.setAccountName("抖音测试账号");
        } else {
            // 默认使用微信平台
            account.setAccountType("wechat");
            account.setAccountName("默认测试账号");
        }
        
        return account;
    }

    @Override
    public void destroy() {
        logger.info("PublishServlet 销毁");
        super.destroy();
    }
}